<template>
  <div class="page-content parking-records">
    <!-- 页面标题和说明 -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold">停车记录</h1>
      <p class="text-gray-500 mt-2">管理和查询所有车辆的停车记录</p>
    </div>

    <!-- 操作栏 -->
    <el-card shadow="hover" class="mb-6">
      <el-form :inline="true" :model="queryParams" class="flex flex-wrap items-end">
        <el-form-item label="停车场">
          <el-select
            v-model="queryParams.parkingLotId"
            placeholder="全部停车场"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in parkingLotOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车牌号">
          <el-input
            v-model="queryParams.carNumber"
            placeholder="请输入车牌号"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="记录状态">
          <el-select
            v-model="queryParams.status"
            placeholder="全部状态"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="(value, key) in ParkingRecordStatus"
              :key="key"
              :label="value"
              :value="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="停车时间">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <div class="flex gap-2">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>查询
            </el-button>
            <el-button @click="resetQuery">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
            <el-button type="success" @click="exportExcel">
              <el-icon><Download /></el-icon>导出
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="mb-6">
      <el-col :md="6" :sm="12" :xs="24" class="mb-4">
        <el-card
          shadow="hover"
          class="h-full bg-gradient-to-r from-blue-50 to-blue-100 dark:from-blue-900 dark:to-blue-800"
        >
          <div class="flex items-center">
            <div class="p-2 rounded-full bg-blue-500 text-white mr-4">
              <i class="i-carbon-document text-2xl"></i>
            </div>
            <div>
              <div class="text-gray-500 text-sm">总记录数</div>
              <div class="text-xl font-bold">{{ statistics.totalRecords }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :md="6" :sm="12" :xs="24" class="mb-4">
        <el-card
          shadow="hover"
          class="h-full bg-gradient-to-r from-green-50 to-green-100 dark:from-green-900 dark:to-green-800"
        >
          <div class="flex items-center">
            <div class="p-2 rounded-full bg-green-500 text-white mr-4">
              <i class="i-carbon-car text-2xl"></i>
            </div>
            <div>
              <div class="text-gray-500 text-sm">当前停车数</div>
              <div class="text-xl font-bold">{{ statistics.currentParking }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :md="6" :sm="12" :xs="24" class="mb-4">
        <el-card
          shadow="hover"
          class="h-full bg-gradient-to-r from-yellow-50 to-yellow-100 dark:from-yellow-900 dark:to-yellow-800"
        >
          <div class="flex items-center">
            <div class="p-2 rounded-full bg-yellow-500 text-white mr-4">
              <i class="i-carbon-currency-yen text-2xl"></i>
            </div>
            <div>
              <div class="text-gray-500 text-sm">今日收入</div>
              <div class="text-xl font-bold">¥{{ statistics.todayIncome }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :md="6" :sm="12" :xs="24" class="mb-4">
        <el-card
          shadow="hover"
          class="h-full bg-gradient-to-r from-red-50 to-red-100 dark:from-red-900 dark:to-red-800"
        >
          <div class="flex items-center">
            <div class="p-2 rounded-full bg-red-500 text-white mr-4">
              <i class="i-carbon-warning text-2xl"></i>
            </div>
            <div>
              <div class="text-gray-500 text-sm">未支付数</div>
              <div class="text-xl font-bold">{{ statistics.unpaidCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-card shadow="hover">
      <el-table
        v-loading="loading"
        :data="recordList"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{
          backgroundColor: 'var(--el-fill-color-light)',
          color: 'var(--el-text-color-primary)'
        }"
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column prop="parkingLotName" label="停车场" min-width="120" />
        <el-table-column prop="carNumber" label="车牌号" min-width="120" align="center" />
        <el-table-column label="入场时间" min-width="160" align="center">
          <template #default="scope">
            <div class="flex flex-col">
              <span>{{ formatDateTime(scope.row.entryTime) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="出场时间" min-width="160" align="center">
          <template #default="scope">
            <span v-if="scope.row.exitTime">{{ formatDateTime(scope.row.exitTime) }}</span>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column label="停车时长" min-width="120" align="center">
          <template #default="scope">
            <span v-if="scope.row.duration">{{ scope.row.duration }}</span>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column label="费用" min-width="100" align="center">
          <template #default="scope">
            <span v-if="scope.row.fee">¥{{ scope.row.fee }}</span>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column label="记录状态" min-width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" effect="light">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="支付状态" min-width="120" align="center">
          <template #default="scope">
            <el-tag
              v-if="scope.row.paymentStatus"
              :type="getPaymentStatusType(scope.row.paymentStatus)"
              effect="light"
            >
              {{ scope.row.paymentStatus }}
            </el-tag>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="handleView(scope.row)">
              查看
            </el-button>
            <el-button
              v-if="scope.row.status === ParkingRecordStatus.PARKING"
              type="success"
              link
              size="small"
              @click="handleExit(scope.row)"
            >
              出场
            </el-button>
            <el-button
              v-if="scope.row.paymentStatus === PaymentStatus.UNPAID"
              type="warning"
              link
              size="small"
              @click="handlePay(scope.row)"
            >
              支付
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="dialogVisible" title="停车记录详情" width="500px" destroy-on-close>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="停车场">{{
          currentRecord.parkingLotName
        }}</el-descriptions-item>
        <el-descriptions-item label="车牌号">{{ currentRecord.carNumber }}</el-descriptions-item>
        <el-descriptions-item label="入场时间">{{
          formatDateTime(currentRecord.entryTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="出场时间">
          {{ currentRecord.exitTime ? formatDateTime(currentRecord.exitTime) : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="停车时长">{{
          currentRecord.duration || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="费用">{{
          currentRecord.fee ? `¥${currentRecord.fee}` : '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="记录状态">
          <el-tag :type="getStatusType(currentRecord.status)">{{ currentRecord.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="支付状态">
          <el-tag
            v-if="currentRecord.paymentStatus"
            :type="getPaymentStatusType(currentRecord.paymentStatus)"
          >
            {{ currentRecord.paymentStatus }}
          </el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentRecord.paymentMethod" label="支付方式">
          {{ currentRecord.paymentMethod }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentRecord.paymentTime" label="支付时间">
          {{ formatDateTime(currentRecord.paymentTime) }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 支付对话框 -->
    <el-dialog v-model="payDialogVisible" title="停车费支付" width="400px" destroy-on-close>
      <div class="flex flex-col items-center">
        <div class="text-2xl font-bold mb-4">¥{{ currentRecord.fee }}</div>
        <el-form :model="payForm" label-width="80px">
          <el-form-item label="支付方式">
            <el-radio-group v-model="payForm.paymentMethod">
              <el-radio-button v-for="(value, key) in PaymentMethod" :key="key" :label="value">
                {{ value }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="flex justify-center mt-4">
          <el-button type="primary" @click="confirmPay">确认支付</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Refresh, Download } from '@element-plus/icons-vue'
  import type { ParkingRecordType } from '@/types/parking'
  import { ParkingRecordStatus, PaymentStatus, PaymentMethod } from '@/types/parking'

  // 查询参数
  const queryParams = reactive({
    parkingLotId: '',
    carNumber: '',
    status: '',
    dateRange: null as [Date, Date] | null
  })

  // 停车场选项
  const parkingLotOptions = ref([
    { value: '1', label: '东门停车场' },
    { value: '2', label: '西区停车场' },
    { value: '3', label: '北门停车场' },
    { value: '4', label: '中心停车场' },
    { value: '5', label: '游客中心停车场' }
  ])

  // 日期快捷选项
  const dateShortcuts = [
    {
      text: '今天',
      value: () => {
        const today = new Date()
        return [today, today]
      }
    },
    {
      text: '昨天',
      value: () => {
        const yesterday = new Date()
        yesterday.setDate(yesterday.getDate() - 1)
        return [yesterday, yesterday]
      }
    },
    {
      text: '最近一周',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setDate(start.getDate() - 7)
        return [start, end]
      }
    },
    {
      text: '最近一个月',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setMonth(start.getMonth() - 1)
        return [start, end]
      }
    }
  ]

  // 表格数据
  const recordList = ref<ParkingRecordType[]>([])
  const loading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

  // 统计数据
  const statistics = ref({
    totalRecords: 0,
    currentParking: 0,
    todayIncome: 0,
    unpaidCount: 0
  })

  // 详情弹窗相关
  const dialogVisible = ref(false)
  const currentRecord = ref<ParkingRecordType>({} as ParkingRecordType)

  // 支付弹窗相关
  const payDialogVisible = ref(false)
  const payForm = reactive({
    paymentMethod: PaymentMethod.WECHAT
  })

  // 组件挂载时获取数据
  onMounted(() => {
    getRecordList()
  })

  // 获取状态样式类型
  const getStatusType = (status: string) => {
    if (status === ParkingRecordStatus.PARKING) return 'primary'
    if (status === ParkingRecordStatus.EXITED) return 'success'
    if (status === ParkingRecordStatus.EXPIRED) return 'danger'
    return 'info'
  }

  // 获取支付状态样式类型
  const getPaymentStatusType = (status: string) => {
    if (status === PaymentStatus.PAID) return 'success'
    if (status === PaymentStatus.UNPAID) return 'danger'
    if (status === PaymentStatus.PENDING) return 'warning'
    if (status === PaymentStatus.REFUNDED) return 'info'
    return 'info'
  }

  // 格式化日期时间
  const formatDateTime = (dateStr: string) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
  }

  // 查询记录列表
  const getRecordList = () => {
    loading.value = true

    // 模拟API请求
    setTimeout(() => {
      const data = generateMockData()
      recordList.value = data
      total.value = 100 // 模拟总数
      updateStatistics()
      loading.value = false
    }, 500)

    // 实际API调用示例
    // parkingService.getRecordList({
    //   page: currentPage.value,
    //   pageSize: pageSize.value,
    //   ...queryParams
    // }).then(res => {
    //   if (res.code === 200) {
    //     recordList.value = res.data.records
    //     total.value = res.data.total
    //     updateStatistics()
    //   }
    //   loading.value = false
    // }).catch(() => {
    //   loading.value = false
    // })
  }

  // 生成模拟数据
  const generateMockData = () => {
    const mockStatus = [
      ParkingRecordStatus.PARKING,
      ParkingRecordStatus.EXITED,
      ParkingRecordStatus.EXPIRED
    ]
    const mockPaymentStatus = [
      PaymentStatus.PAID,
      PaymentStatus.UNPAID,
      PaymentStatus.PENDING,
      null
    ]
    const mockPaymentMethod = [
      PaymentMethod.WECHAT,
      PaymentMethod.ALIPAY,
      PaymentMethod.CASH,
      PaymentMethod.CARD,
      null
    ]

    return Array.from({ length: pageSize.value }, (_, i) => {
      const id = (currentPage.value - 1) * pageSize.value + i + 1
      const parkingLotId = Math.floor(Math.random() * 5) + 1
      const status = mockStatus[Math.floor(Math.random() * mockStatus.length)]

      // 根据状态生成不同的数据
      const entryTime = new Date(Date.now() - Math.floor(Math.random() * 1000000000))
      const exitTime =
        status === ParkingRecordStatus.PARKING
          ? null
          : new Date(entryTime.getTime() + Math.floor(Math.random() * 86400000))

      const duration = exitTime
        ? `${Math.floor((exitTime.getTime() - entryTime.getTime()) / 3600000)}小时${Math.floor(((exitTime.getTime() - entryTime.getTime()) % 3600000) / 60000)}分钟`
        : null

      const fee = exitTime ? Math.floor(Math.random() * 50) + 10 : null

      const paymentStatus =
        status === ParkingRecordStatus.PARKING
          ? null
          : mockPaymentStatus[Math.floor(Math.random() * mockPaymentStatus.length)]

      const paymentMethod =
        paymentStatus === PaymentStatus.PAID
          ? mockPaymentMethod[Math.floor(Math.random() * (mockPaymentMethod.length - 1))]
          : null

      const paymentTime =
        paymentStatus === PaymentStatus.PAID
          ? new Date(exitTime!.getTime() + Math.floor(Math.random() * 600000))
          : null

      return {
        id,
        parkingLotId,
        parkingLotName:
          parkingLotOptions.value.find((option) => option.value === String(parkingLotId))?.label ||
          '',
        carNumber: `粤A${Math.floor(Math.random() * 90000) + 10000}`,
        entryTime: entryTime.toISOString(),
        exitTime: exitTime?.toISOString() || null,
        duration,
        fee,
        status,
        paymentStatus,
        paymentMethod,
        paymentTime: paymentTime?.toISOString() || null
      } as ParkingRecordType
    })
  }

  // 更新统计数据
  const updateStatistics = () => {
    // 获取当前时间的日期部分
    const today = new Date().toDateString()

    // 统计当前停车中的记录数
    const currentParking = recordList.value.filter(
      (record) => record.status === ParkingRecordStatus.PARKING
    ).length

    // 统计今日收入
    const todayIncome = recordList.value
      .filter(
        (record) =>
          record.paymentStatus === PaymentStatus.PAID &&
          new Date(record.paymentTime!).toDateString() === today
      )
      .reduce((total, record) => total + (record.fee || 0), 0)

    // 统计未支付的记录数
    const unpaidCount = recordList.value.filter(
      (record) => record.paymentStatus === PaymentStatus.UNPAID
    ).length

    statistics.value = {
      totalRecords: total.value,
      currentParking,
      todayIncome,
      unpaidCount
    }
  }

  // 查询
  const handleSearch = () => {
    currentPage.value = 1
    getRecordList()
  }

  // 重置查询
  const resetQuery = () => {
    Object.keys(queryParams).forEach((key) => {
      queryParams[key as keyof typeof queryParams] = key === 'dateRange' ? null : ''
    })
    currentPage.value = 1
    getRecordList()
  }

  // 导出Excel
  const exportExcel = () => {
    ElMessage.success('数据导出成功')
  }

  // 查看详情
  const handleView = (row: ParkingRecordType) => {
    currentRecord.value = { ...row }
    dialogVisible.value = true
  }

  // 车辆出场
  const handleExit = (row: ParkingRecordType) => {
    ElMessageBox.confirm('确认该车辆已出场?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        // 模拟API调用
        setTimeout(() => {
          ElMessage.success('车辆出场成功')
          getRecordList()
        }, 500)
      })
      .catch(() => {})
  }

  // 处理支付
  const handlePay = (row: ParkingRecordType) => {
    currentRecord.value = { ...row }
    payDialogVisible.value = true
  }

  // 确认支付
  const confirmPay = () => {
    // 模拟API调用
    setTimeout(() => {
      payDialogVisible.value = false
      ElMessage.success('支付成功')
      getRecordList()
    }, 1000)
  }

  // 删除记录
  const handleDelete = (row: ParkingRecordType) => {
    ElMessageBox.confirm('确认删除该停车记录?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        // 模拟API调用
        setTimeout(() => {
          ElMessage.success('删除成功')
          getRecordList()
        }, 500)
      })
      .catch(() => {})
  }

  // 处理页码大小变化
  const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
    getRecordList()
  }

  // 处理页码变化
  const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getRecordList()
  }
</script>

<style lang="scss" scoped>
  .parking-records {
    // 自定义样式可以在这里添加
  }
</style>
